<template>
    <!-- 搜索相关 start -->
    <el-form :model="queryParams" size="default" :inline="true" v-show="showSearch" label-width="38px">
        <el-form-item label="年月份" prop="user" label-width="70px">
            <el-date-picker v-model="selectedYearMonth" type="month" placeholder="请选择年月份" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="default" @click="handleGetList">搜索</el-button>
        </el-form-item>
    </el-form>
    <!-- 搜索相关 end -->

    <!-- 表格部分 start -->
    <el-table @row-contextmenu="rightClickFn" @contextmenu.prevent :data="tableData" style="width: 1230px"
        max-height="550" show-summary>
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="55" :index="indexMethod" />
        <el-table-column prop="catering" label="餐饮" width="90">
            <template #default="{ row }">
                <el-tooltip class="item" effect="dark" :content="row.cateringRemark" placement="top">
                    <el-input v-model="row.catering" v-if="editingRow === row.id"></el-input>
                    <span v-if="editingRow !== row.id">{{ row.catering }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="dailyShopping" label="日常购物" width="90">
            <template #default="{ row }">
                <el-tooltip class="item" effect="dark" :content="row.dailyShoppingRemark" placement="top">
                    <el-input v-model="row.dailyShopping" v-if="editingRow === row.id"></el-input>
                    <span v-if="editingRow !== row.id">{{ row.dailyShopping }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="babyShopping" label="宝宝购物" width="90">
            <template #default="{ row }">
                <el-tooltip class="item" effect="dark" :content="row.babyShoppingRemark" placement="top">
                    <el-input v-model="row.babyShopping" v-if="editingRow === row.id"></el-input>
                    <span v-if="editingRow !== row.id">{{ row.babyShopping }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="waterElectricityGas" label="水电煤" width="90">
            <template #default="{ row }">
                <el-tooltip class="item" effect="dark" :content="row.waterElectricityGasRemark" placement="top">
                    <el-input v-model="row.waterElectricityGas" v-if="editingRow === row.id"></el-input>
                    <span v-if="editingRow !== row.id">{{ row.waterElectricityGas }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="car" label="车" width="90">
            <template #default="{ row }">
                <el-tooltip class="item" effect="dark" :content="row.carRemark" placement="top">
                    <el-input v-model="row.car" v-if="editingRow === row.id"></el-input>
                    <span v-if="editingRow !== row.id">{{ row.car }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机" width="90">
            <template #default="{ row }">
                <el-tooltip class="item" effect="dark" :content="row.phoneRemark" placement="top">
                    <el-input v-model="row.phone" v-if="editingRow === row.id"></el-input>
                    <span v-if="editingRow !== row.id">{{ row.phone }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="travel" label="出行" width="90">
            <template #default="{ row }">
                <el-tooltip class="item" effect="dark" :content="row.travelRemark" placement="top">
                    <el-input v-model="row.travel" v-if="editingRow === row.id"></el-input>
                    <span v-if="editingRow !== row.id">{{ row.travel }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="healthcare" label="医疗" width="90">
            <template #default="{ row }">
                <el-tooltip class="item" effect="dark" :content="row.healthcareRemark" placement="top">
                    <el-input v-model="row.healthcare" v-if="editingRow === row.id"></el-input>
                    <span v-if="editingRow !== row.id">{{ row.healthcare }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="humanGift" label="人情礼物" width="90">
            <template #default="{ row }">
                <el-tooltip class="item" effect="dark" :content="row.humanGiftRemark" placement="top">
                    <el-input v-model="row.humanGift" v-if="editingRow === row.id"></el-input>
                    <span v-if="editingRow !== row.id">{{ row.humanGift }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="others" label="其他" width="90">
            <template #default="{ row }">
                <el-tooltip class="item" effect="dark" :content="row.othersRemark" placement="top">
                    <el-input v-model="row.others" v-if="editingRow === row.id"></el-input>
                    <span v-if="editingRow !== row.id">{{ row.others }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
            <template #default="scope">
                <el-button type="primary" @click="editRow(scope.$index, scope.row)">编辑</el-button>
                <el-button type="primary" @click="saveAccounting(scope.row)">保存</el-button>
                <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled"
                    icon-color="#626AEF" title="确定要删除这一行么？"
                    @confirm="handleDeleteConfirmEvent(scope.$index, scope.row)">
                    <template #reference>
                        <el-button type="primary" :icon="Delete" />
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>
    <el-button class="mt-4" style="width: 1230px"  @click="onAddItem" >
        新增一条
    </el-button>

    <RightMenu :textList="textList" :clickXY="clickXY"></RightMenu>
    <!-- 表格部分 end -->

    <!-- 插入备注对话框 start-->
    <el-dialog v-model="insertRemarkDialogVisible" title="备注" width="500">
        <el-form :model="rowData">
            <el-form-item label="备注" :label-width="formLabelWidth">
                <el-input v-model="tempRemarkContent" type="textarea" autocomplete="off" :rows="5" maxlength="50" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="insertRemarkDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveRemarkFun">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 插入备注对话框 end -->
</template>
<script setup lang="ts">
import RightMenu from '@/views/rightMenu/rightMenu.vue';
import { reactive, ref, watchEffect, nextTick, onMounted } from 'vue';
import { showErrorMsg, showSuccessMsg, formatDate, indexMethod } from '@/api/common';
import type { OnlyIdRequest, ApiResponse } from '@/api/common';
import type { QueryParams, Accounting, MenuItem, ClickXY } from '@/api/accounting/accounting.ts'
import { deleteAccounting, listByYearMonth, save } from '@/api/accounting/accounting'
import type { Column } from 'element-plus';
import { Delete, InfoFilled } from '@element-plus/icons-vue'
let onlyIdRequest = reactive<OnlyIdRequest>({
    id: null,
})
const showSearch = ref(true)
const selectedYearMonth = ref('')
// mock data
// let tableData = ref<Accounting[]>([
//     {
//         id: null,
//         // 记账年份
//         accountingYear: 2024,
//         // 记账月份
//         accountingMonth: 2,
//         // 餐饮
//         catering: 12.23,
//         cateringRemark: '2024-05-22',
//         // 日常购物
//         dailyShopping: 12.23,
//         dailyShoppingRemark: null,
//         // 宝宝购物
//         babyShopping: 12.23,
//         babyShoppingRemark: null,
//         // 水电煤
//         waterElectricityGas: 12.23,
//         waterElectricityGasRemark: null,
//         // 车
//         car: 12.23,
//         carRemark: null,
//         // 手机
//         phone: 12.23,
//         phoneRemark: null,
//         // 出行
//         travel: 12.23,
//         travelRemark: null,
//         // 医疗
//         healthcare: 12.23,
//         healthcareRemark: null,
//         // 人情礼物
//         humanGift: 12.23,
//         humanGiftRemark: null,
//         // 其他
//         others: 12.23,
//         othersRemark: null,
//     },
// ])
let tableData = ref<Accounting[]>([]);
let rowData = reactive({})
const insertRemarkDialogVisible = ref(false)
const formLabelWidth = '60px'
const onAddItem = () => {
    if (tableData.value) {
        let needBlock = false
        tableData.value.forEach((row) => {
            if (row.id === null) {
                needBlock = true;
            }
        });
        if (needBlock) {
            showErrorMsg('请先保存前面新增的数据！');
            return;
        }
    }
    tableData.value.push({
        id: null,
        // 记账年份
        accountingYear: null,
        // 记账月份
        accountingMonth: null,
        // 餐饮
        catering: null,
        cateringRemark: null,
        // 日常购物
        dailyShopping: null,
        dailyShoppingRemark: null,
        // 宝宝购物
        babyShopping: null,
        babyShoppingRemark: null,
        // 水电煤
        waterElectricityGas: null,
        waterElectricityGasRemark: null,
        // 车
        car: null,
        carRemark: null,
        // 手机
        phone: null,
        phoneRemark: null,
        // 出行
        travel: null,
        travelRemark: null,
        // 医疗
        healthcare: null,
        healthcareRemark: null,
        // 人情礼物
        humanGift: null,
        humanGiftRemark: null,
        // 其他
        others: null,
        othersRemark: null,
    })
}
let editingRow = ref<number | null>(null)
const editRow = (index: number, row: Accounting) => {
    if (row === null) {
        editingRow.value = null;
        return;
    }
    // 如果点击的是同一行，则取消编辑
    if (editingRow.value === row.id) {
        editingRow.value = null;
    } else {
        editingRow.value = row.id;
    }
}
const saveAccounting = (row: Accounting) => {
    calYearMonth();
    row.accountingYear = queryParams.accountingYear;
    row.accountingMonth = queryParams.accountingMonth;
    save(row).then((res: ApiResponse<string>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            tempRemarkContent.value = null;
            tempRemarkLabel.value = null;
            tempRemarkRow.value = null;
            showSuccessMsg('保存成功！')
            handleGetList();
        }
    });
}

const textList = reactive<MenuItem[]>([]);
const clickXY = reactive<ClickXY>({ position: { x: 0, y: 0 } });
const rightClickFn = (row: Accounting, column: Column, event: MouseEvent) => {
    Object.assign(textList,
        [
            {
                // 使用回调函数的方式fnn，定义在父组件，在子组件调用即可触发
                icon: 'edit', text: '备注', fnn: saveRemarkCallback,
                params: { row, column, event },
            },
            {
                icon: 'delete', text: '删除', fnn: del,
                params: { row, column, event },
            }
        ]
    )
    Object.assign(clickXY,
        {
            position: {
                x: event.clientX,
                y: event.clientY
            }
        }
    )
}
let tempRemarkContent = ref<string | null>(null)
let tempRemarkLabel = ref<string | null>(null)
let tempRemarkRow = ref<Accounting | null>(null)
const saveRemarkCallback = (val: MenuItem) => {
    rowData = val.params.row
    tempRemarkLabel.value = val.params.column.label;
    tempRemarkRow.value = val.params.row;
    tempRemarkContent.value = remarkGetData(val.params.column.label, val.params.row)
    insertRemarkDialogVisible.value = true;
}
const saveRemarkFun = () => {
    insertRemarkDialogVisible.value = false;
    remarkSetData();
    tempRemarkContent.value = null;
}
const remarkGetData = (label: string, row: Accounting): string | null => {
    switch (label) {
        case '餐饮': return row.cateringRemark;
        case '日常购物': return row.dailyShoppingRemark;
        case '宝宝购物': return row.babyShoppingRemark;
        case '水电煤': return row.waterElectricityGasRemark;
        case '车': return row.carRemark;
        case '手机': return row.phoneRemark;
        case '出行': return row.travelRemark;
        case '医疗': return row.healthcareRemark;
        case '人情礼物': return row.humanGiftRemark;
        case '其他': return row.othersRemark;
        default: return '';
    }
}
const remarkSetData = () => {
    switch (tempRemarkLabel.value) {
        case '餐饮':
            tempRemarkRow.value!.cateringRemark = tempRemarkContent.value;
            break;
        case '日常购物':
            tempRemarkRow.value!.dailyShoppingRemark = tempRemarkContent.value;
            break;
        case '宝宝购物':
            tempRemarkRow.value!.babyShoppingRemark = tempRemarkContent.value;
            break;
        case '水电煤':
            tempRemarkRow.value!.waterElectricityGasRemark = tempRemarkContent.value;
            break;
        case '车':
            tempRemarkRow.value!.carRemark = tempRemarkContent.value;
            break;
        case '手机':
            tempRemarkRow.value!.phoneRemark = tempRemarkContent.value;
            break;
        case '出行':
            tempRemarkRow.value!.travelRemark = tempRemarkContent.value;
            break;
        case '医疗':
            tempRemarkRow.value!.healthcareRemark = tempRemarkContent.value;
            break;
        case '人情礼物':
            tempRemarkRow.value!.humanGiftRemark = tempRemarkContent.value;
            break;
        case '其他':
            tempRemarkRow.value!.othersRemark = tempRemarkContent.value;
            break;
        default:
            break;
    }
}
const del = (val: MenuItem) => { }
let queryParams = reactive<QueryParams>({
    accountingYear: null,
    accountingMonth: null,
})
const calYearMonth = () => {
    let selectedYearMonthTemp = formatDate(selectedYearMonth.value);
    let yearMonthTemp = selectedYearMonthTemp.split('-');
    queryParams.accountingYear = parseInt(yearMonthTemp[0], 10);
    queryParams.accountingMonth = parseInt(yearMonthTemp[1], 10);
}
const handleGetList = () => {
    if (!selectedYearMonth.value) {
        showErrorMsg('请选择年月份！')
        return;
    }
    calYearMonth();
    listByYearMonth(queryParams).then((res: ApiResponse<Accounting[]>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            tableData.value = res.data;
        }
    });
}
const handleDeleteConfirmEvent = (index: number, row: Accounting) => {
    onlyIdRequest.id = row.id;
    deleteAccounting(onlyIdRequest).then((res: ApiResponse<string>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            showSuccessMsg("删除成功")
            handleGetList();
        }
    });
}
</script>
<style scoped lang="scss"></style>